/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package weixin;

import Auto.WeiXinAuto;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author jerry
 */
public class AllSendMain extends javax.swing.JFrame {

    /**
     * 一开始就准备好面板
     */
    public sendingpanel SendingPanel = new sendingpanel();

    /**
     * 发送的线程
     */
    public Thread[] SendThread;
    /**
     * 发送线程的状态
     */
    public boolean SendStatus = true;

    /**
     * 默认的发送暂停状态
     */
    public boolean SendStopStatus = false;

    /**
     * 线程休眠间隔时间
     */
    public int SleepTime = 1000;

    /**
     * 好友统计数
     */
    public int AllFriendCount = 0;

    /**
     * Creates new form AllSendMain
     */
    public AllSendMain() {
        initComponents();
        //设置居中
        this.setLocationRelativeTo(null);
        ImageIcon icon = new ImageIcon(this.getClass().getResource("/images/weixin_logo.png"));
        this.setIconImage(icon.getImage());

        SendingPanel.setBounds(0, 0, send_panel.getWidth(), send_panel.getHeight());
        SendingPanel.setVisible(false);
        add(SendingPanel);
        //监听终止按钮
        SendingPanel.sending_over_button.addActionListener((ActionEvent e) -> {
            SendStatus = false;
            StopOrStartThread(true);
            ChangeMainShow(false);
        });
        //监听暂停按钮
        SendingPanel.sending_stop_button.addActionListener((ActionEvent e) -> {
            //暂停或重新开始
            if (SendStopStatus) {
                //如果是暂停了,就启用
                StopOrStartThread(true);
            } else {
                StopOrStartThread(false);
            }
        });

    }

    /**
     * 启动或暂停群发线程
     *
     * @param Start
     */
    private void StopOrStartThread(boolean Start) {
        //start 是真  就启动
        if (Start) {
            //如果是暂停了,就启用

            SendStopStatus = false;
            //启用的时候要循环线程
            for (int i = 0; i < SendThread.length; i++) {
                Thread thread = SendThread[i];

                synchronized (thread) {
                    thread.notifyAll();
                }
            }
            SendingPanel.sending_stop_button.setText("暂停群发");
        } else {
            //否则就暂停

            SendStopStatus = true;
            SendingPanel.sending_stop_button.setText("继续群发");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        send_panel = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        send_button = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        send_text = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        send_sleep_time = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        send_select_type_women = new javax.swing.JCheckBox();
        send_select_type_man = new javax.swing.JCheckBox();
        send_select_type_group = new javax.swing.JCheckBox();
        send_select_type_friend = new javax.swing.JCheckBox();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("消息群发");

        jLabel5.setText("秒/条");

        send_button.setBackground(new Color(233,233,233,0));
        send_button.setFont(new java.awt.Font("Lucida Grande", 1, 12)); // NOI18N
        send_button.setForeground(new java.awt.Color(255, 255, 255));
        send_button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/button_black.png"))); // NOI18N
        send_button.setText("开始群发");
        send_button.setBorder(null);
        send_button.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        send_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_buttonActionPerformed(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        send_text.setColumns(20);
        send_text.setLineWrap(true);
        send_text.setRows(5);
        send_text.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        jScrollPane1.setViewportView(send_text);

        jLabel4.setText("发送内容:");

        send_sleep_time.setText("1");

        jLabel3.setText("发送间隔:");

        jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
        jLabel2.setText("发送配置");

        send_select_type_women.setText("女士");

        send_select_type_man.setText("男士");

        send_select_type_group.setText("群组");

        send_select_type_friend.setText("朋友");
        send_select_type_friend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_select_type_friendActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
        jLabel1.setText("选择群发对象:");

        javax.swing.GroupLayout send_panelLayout = new javax.swing.GroupLayout(send_panel);
        send_panel.setLayout(send_panelLayout);
        send_panelLayout.setHorizontalGroup(
            send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 630, Short.MAX_VALUE)
            .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(send_panelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jSeparator1)
                        .addComponent(jSeparator2)
                        .addComponent(jScrollPane1)
                        .addGroup(send_panelLayout.createSequentialGroup()
                            .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addGroup(send_panelLayout.createSequentialGroup()
                                    .addComponent(send_select_type_friend)
                                    .addGap(0, 0, 0)
                                    .addComponent(send_select_type_group, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(send_panelLayout.createSequentialGroup()
                                    .addComponent(send_select_type_man)
                                    .addGap(0, 0, 0)
                                    .addComponent(send_select_type_women))
                                .addComponent(jLabel2)
                                .addComponent(jLabel4)
                                .addGroup(send_panelLayout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addGap(18, 18, 18)
                                    .addComponent(send_sleep_time, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel5)))
                            .addGap(452, 452, 452))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, send_panelLayout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addComponent(send_button)))
                    .addContainerGap()))
        );

        send_panelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {send_select_type_friend, send_select_type_group, send_select_type_man, send_select_type_women});

        send_panelLayout.setVerticalGroup(
            send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 432, Short.MAX_VALUE)
            .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(send_panelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(send_select_type_friend)
                        .addComponent(send_select_type_group))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(send_select_type_man)
                        .addComponent(send_select_type_women))
                    .addGap(49, 49, 49)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(send_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(send_sleep_time, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(send_button)
                    .addContainerGap()))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(send_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(send_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void send_select_type_friendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send_select_type_friendActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_send_select_type_friendActionPerformed

    /**
     * 点击开始群发按钮的事件
     *
     * @param evt
     */
    private void send_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send_buttonActionPerformed

        //根据选择的类型筛选要发送的信息
        //最后得出要发送的用户的username
        HashMap get_all_send_friends = GetSendUserName();

        SendingPanel.sending_bar.setMaximum(AllFriendCount);
        SendingPanel.sending_bar.setMinimum(0);
        SendingPanel.sending_bar.setValue(0);
        //界面效果改变
        ChangeMainShow(true);
        //开始建立新的线程
        StartSend(get_all_send_friends);
    }//GEN-LAST:event_send_buttonActionPerformed

    /**
     * 开始群发指定列表内的用户指定的信息
     *
     * @param get_all_send_friends
     */
    public void StartSend(HashMap get_all_send_friends) {
        //获得账号的总数
        int weixin_count = get_all_send_friends.size();
        SendThread = new Thread[weixin_count];
        int now_int = 0;
        SendStatus = true;
        //用一个线程来执行循环
        new Thread(() -> {
            //这个线程仅仅是循环
            Iterator all_iter = get_all_send_friends.entrySet().iterator();
            while (all_iter.hasNext()) {
                Map.Entry next = (Map.Entry) all_iter.next();
                String weixin_uid = next.getKey().toString();
                HashMap one_weixin = (HashMap) next.getValue();
                //再循环
                //建立新线程
                SendThread[now_int] = new Thread(() -> {
                    WhileOneWeixin(one_weixin, SendThread[now_int], weixin_uid);
                });
                SendThread[now_int].start();

            }
        }).start();
    }

    /**
     * 循环其中一个微信
     *
     * @param one_weixin
     * @param one_Thread
     * @param weixin_uid
     */
    public void WhileOneWeixin(HashMap one_weixin, Thread one_Thread, String weixin_uid) {

        WeiXinAuto use_weixin_auto = (WeiXinAuto) AdminMain.AllWeiXinAutos.get(weixin_uid);
        //一个微信下面要发送的账号
        Iterator one_iter = one_weixin.entrySet().iterator();
        while (one_iter.hasNext() && SendStatus) {
            Map.Entry one_user = (Map.Entry) one_iter.next();
            String user_name = one_user.getKey().toString();
            String nick_name = one_user.getValue().toString();
            //显示用户名
            SendingPanel.sending_nick_name.setText("<html>" + nick_name + "</html>");

            //更新进度条
            int new_value = SendingPanel.sending_bar.getValue() + 1;
            SendingPanel.sending_count.setText(new_value + "/" + AllFriendCount);
            SendingPanel.sending_bar.setValue(new_value);

            //调用发送方法
            boolean result_send = use_weixin_auto.SendMsgToFriend(user_name, send_text.getText());
            if (result_send) {
                SendingPanel.sending_result.append(nick_name + "发送成功.");
            } else {
                SendingPanel.sending_result.append(nick_name + "发送失败!!");
            }
            //暂停线程
            synchronized (one_Thread) {
                if (SendStopStatus) {
                    try {
                        one_Thread.wait();
                    } catch (InterruptedException ex) {
                        System.err.println("暂停线程出错");
                    }
                }
            }

            try {
                //每发送一个就延迟一下
                Thread.sleep(SleepTime);
            } catch (InterruptedException ex) {
                System.err.println("群发休眠出错");
            }
        }
        //到此发送完毕!
        JOptionPane.showMessageDialog(null, "消息群发完毕!");
        dispose();

    }

    /**
     * 根据选择的类型筛选出要发送用户的username
     * <br>[微信账号][发送username]
     *
     * @return
     */
    private HashMap GetSendUserName() {
        //获得发送选项
        boolean send_type_friend = send_select_type_friend.isSelected();
        boolean send_type_group = send_select_type_group.isSelected();
        boolean send_type_man = send_select_type_man.isSelected();
        boolean send_type_women = send_select_type_women.isSelected();
        //发送时间间隔
        String send_sleep_string = send_sleep_time.getText();
        if (send_sleep_string.equals("")) {
            send_sleep_string = "1";
            send_sleep_time.setText("1");
        }
        SleepTime = Integer.parseInt(send_sleep_string) * 1000;

        //开始循环得出要返回的数据
        HashMap back_all_hash = new HashMap();

        int all_f_count = 0;
        //循环全部的auto
        Iterator a_iter = AdminMain.AllWeiXinAutos.entrySet().iterator();

        while (a_iter.hasNext()) {
            Map.Entry one_entry = (Map.Entry) a_iter.next();
            String key_string = one_entry.getKey().toString();
            WeiXinAuto one_weixin_auto = (WeiXinAuto) one_entry.getValue();
            System.err.println("循环微信:" + key_string);
            //得到全部好友json
            JsonArray all_friends = one_weixin_auto.AllfriendsList;
            //准备新的Hash 用来存放
            HashMap one_select_friends = new HashMap();
            //遍历全部好友

            Iterator<JsonElement> oa_iter = all_friends.iterator();
            while (oa_iter.hasNext()) {
                JsonObject next = (JsonObject) oa_iter.next();
                String one_username = next.get("UserName").getAsString();
                String one_nick_name = next.get("NickName").getAsString();
                String one_user_sex = next.get("Sex").getAsString();
                //进行匹配,不匹配就直接跳过,默认为通过
                boolean is_flag_ok = false;
                boolean is_sex_ok = false;

//                System.err.println(show_count + "循环朋友:" + one_nick_name + "(" + one_username);
                //如果要求好友并是好友则通过
                if (send_type_friend && !one_username.contains("@@")) {
                    is_flag_ok = true;
                }
                if (send_type_group && one_username.contains("@@")) {
                    is_flag_ok = true;
                }
                if (send_type_man && one_user_sex.equals("1")) {
                    is_sex_ok = true;
                }
                if (send_type_women && one_user_sex.equals("2")) {
                    is_sex_ok = true;
                }
                //以上检测完毕,是false就是不匹配,不加入
                //不是好友也不是公众号,就绝对跳过
                if (!is_flag_ok && !is_sex_ok) {
                    continue;//跳过
                }

                //加入这个用户
                one_select_friends.put(one_username, one_nick_name);

                all_f_count++;
            }
            //循环完毕,加入总的hash
            back_all_hash.put(key_string, one_select_friends);
        }

        AllFriendCount = all_f_count;

        return back_all_hash;
    }

    /**
     * 改变面板切换
     *
     * @param panelstatus
     */
    private void ChangeMainShow(boolean panelstatus) {
        //如果是发送中的状态
        if (panelstatus) {

            send_panel.setVisible(false);
            SendingPanel.setVisible(true);
        } else {
            send_panel.setVisible(true);
            SendingPanel.setVisible(false);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AllSendMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AllSendMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AllSendMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AllSendMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new AllSendMain().setVisible(true);
//            }
//        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton send_button;
    private javax.swing.JPanel send_panel;
    private javax.swing.JCheckBox send_select_type_friend;
    private javax.swing.JCheckBox send_select_type_group;
    private javax.swing.JCheckBox send_select_type_man;
    private javax.swing.JCheckBox send_select_type_women;
    private javax.swing.JTextField send_sleep_time;
    private javax.swing.JTextArea send_text;
    // End of variables declaration//GEN-END:variables
}
